import processing.net.*;

class Wiimote {
  Wiimote(PApplet applet) {
    client = new Client(applet, "localhost", 0x4A54);
  }
  void update() {
    while (client.available() > 80) {
      if (buffer == null) {
        buffer = new int[80];
      }
      for (int i = 0; i < 80; i++) {
        buffer[i] = client.read();
      }
    }
    if (buffer == null) {
      return;
    }
    bufferPos = 1;
    batteryLevel = (float)readByte() / 0xC8;
    buttonState = readShort();
    x = readFloat();
    y = readFloat();
    z = readFloat();
    extensionType = readByte();
    bufferPos = 0;
  }
  int readByte() {
    return buffer[bufferPos++];
  }
  int readShort() {
    return (buffer[bufferPos++] << 8) | buffer[bufferPos++];
  }
  float readFloat() {
    return Float.intBitsToFloat((buffer[bufferPos++] << 24)
        | (buffer[bufferPos++] << 16)
        | (buffer[bufferPos++] << 8)
        | buffer[bufferPos++]);
  }
  
  Client client;
  int[] buffer;
  int bufferPos;
  
  float batteryLevel;
  int buttonState;
  float x, y, z;
  int extensionType;
}

